package com.admin.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.admin.bean.ProductBean;

@Repository
public class ProductDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	private QueryRunner queryRunner;

	/**
	 * 添加新的产品
	 * @param product
	 * @return
	 */
	public int insertProduct(String productName){
		final String sql = "insert into product(productName)values(?)";
		return jdbcTemplate.update(sql, productName);
	}
	
	/**
	 * 分页查询产品
	 * @return
	 * @throws SQLException
	 */
	public List<ProductBean> findProduct(int start,int pageSize) throws SQLException{
		final String sql = "select * from product order by createTime desc limit ?,?";
		return queryRunner.query(sql, new BeanListHandler<ProductBean>(ProductBean.class),new Object[]{start,pageSize});
	}
	
	/**
	 * 查询所有的产品
	 * @return
	 * @throws SQLException
	 */
	public List<ProductBean> findAllProduct() throws SQLException{
		final String sql = "select * from product";
		return queryRunner.query(sql, new BeanListHandler<ProductBean>(ProductBean.class));
	}
	
	/**
	 * 统计产品总数
	 * @return
	 */
	public int findCount(){
		final String sql = "select count(0) from product";
		return jdbcTemplate.queryForInt(sql);
	}
	
	/**
	 * 根据ID获取产品信息
	 * @param productId
	 * @return
	 * @throws SQLException
	 */
	public ProductBean findProductById(int productId) throws SQLException{
		final String sql = "select * from product where productId = ?";
		return queryRunner.query(sql, new BeanHandler<ProductBean>(ProductBean.class), productId);
	}
	
	/**
	 * 删除产品
	 * @param productId
	 * @return
	 */
	public int delProduct(int productId){
		final String sql = "delete from product where productId = ?";
		return jdbcTemplate.update(sql, productId);
	}
	
	/**
	 * 删除产品
	 * @param product
	 * @return
	 */
	public int updateProduct(ProductBean product){
		final String sql = "update product set productName = ? where productId = ?";
		return jdbcTemplate.update(sql, new Object[]{product.getProductName(),product.getProductId()});
	}
}
